<?php

namespace app\api\controller;

use app\admin\model\DormitoryDorm;
use app\admin\model\DormitoryDormBed;
use app\admin\model\Student;
use app\common\controller\Api;
use \app\common\model;
use think\Db;

/**
 * 行为接口
 */
class Behavior extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['headlines', 'recordMe', 'iRecord', 'addRecord'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (点评头条)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/8 15:51)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/headlines)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1565250669",
    "data": [
    {
    "id": 12,
    "record_user_id": 21,
    "username": "1234561001",
    "nickname": "1111",
    "garden_number": "1",
    "garden_name": "雅园",
    "building_number": "1",
    "building_name": "1号楼",
    "dorm_number": "1-101",
    "bed_number": "1-10101"
    },
    {
    "id": 11,
    "record_user_id": 21,
    "username": "1234561001",
    "nickname": "1111",
    "garden_number": "1",
    "garden_name": "雅园",
    "building_number": "1",
    "building_name": "1号楼",
    "dorm_number": "1-101",
    "bed_number": "1-10101"
    }
    ]
    })
     */
    public function headlines()
    {
        //两条头条
        $results = model\BehaviorRecord::alias('a')
            ->join('__USER__ b', 'b.id = a.record_user_id', 'left')
            ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
            ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number', 'left')
            ->field('a.id,a.record_user_id,b.username,b.nickname,a.garden_number,c.name as garden_name,a.building_number,d.name as building_name,a.dorm_number,a.bed_number')
            ->order('a.id', 'desc')
            ->limit(5)
            ->select();

        $this->success('', $results);
    }

    /**
     * @ApiTitle    (行为列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 17:35)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/behaviorList)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564565835",
    "data": {
    "dorm": {
    "positive": [
    {
    "id": 8,
    "name": "参加趣味活动",
    "type": 1,
    "type_text": "积极的",
    "score": 5
    }
    ],
    "negative": [
    {
    "id": 24,
    "name": "脱贫成果",
    "type": 2,
    "type_text": "消极的",
    "score": 20
    }
    ]
    },
    "bed": {
    "positive": [
    {
    "id": 10,
    "name": "文明家庭",
    "type": 1,
    "type_text": "积极的",
    "score": 5
    }
    ],
    "negative": [
    {
    "id": 29,
    "name": "111",
    "type": 2,
    "type_text": "消极的",
    "score": 6
    },
    {
    "id": 30,
    "name": "111",
    "type": 2,
    "type_text": "消极的",
    "score": 7
    }
    ]
    }
    }
    })
     */
    public function behaviorList()
    {
        $result = model\Behavior::where('status', model\Behavior::NORMAL)
            ->field('id,name,category_id,type,score')
            ->select();

        if ($result)
            $result = collection($result)->append(['type_text', 'category_text'])->toArray();

        $data = [];
        foreach ($result as $key => $value) {

            if (model\Behavior::DORM == $value['category_id']) {
                if (model\Behavior::POSITIVE == $value['type']) {
                    $data['dorm']['positive'][] = [
                        'id' => $value['id'],
                        'name' => $value['name'],
                        'type' => $value['type'],
                        'type_text' => $value['type_text'],
                        'score' => $value['score'],
                    ];
                } else if (model\Behavior::NEGATIVE == $value['type']) {
                    $data['dorm']['negative'][] = [
                        'id' => $value['id'],
                        'name' => $value['name'],
                        'type' => $value['type'],
                        'type_text' => $value['type_text'],
                        'score' => $value['score'],
                    ];
                }

            } else {

                if (model\Behavior::POSITIVE == $value['type']) {
                    $data['bed']['positive'][] = [
                        'id' => $value['id'],
                        'name' => $value['name'],
                        'type' => $value['type'],
                        'type_text' => $value['type_text'],
                        'score' => $value['score'],
                    ];
                } else if (model\Behavior::NEGATIVE == $value['type']) {
                    $data['bed']['negative'][] = [
                        'id' => $value['id'],
                        'name' => $value['name'],
                        'type' => $value['type'],
                        'type_text' => $value['type_text'],
                        'score' => $value['score'],
                    ];
                }

            }
        }

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (点评寝室及床位)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/8 15:08)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/addBehaviorRecord)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="dorm", type="array", required=true, description="寝室数据", sample="")
     * @ApiParams   (name="dorm[id]", type="int", required=false, description="寝室id", sample="")
     * @ApiParams   (name="dorm[comment]", type="text", required=false, description="点评说明", sample="")
     * @ApiParams   (name="dorm[images]", type="text", required=false, description="图片链接 多图以,分割", sample="")
     * @ApiParams   (name="dorm[behavior_ids]", type="array", required=false, description="点评寝室的行为ids", sample="")
     * @ApiParams   (name="bed", type="array", required=true, description="床位数据", sample="")
     * @ApiParams   (name="bed[0][id]", type="int", required=false, description="床位数据", sample="")
     * @ApiParams   (name="bed[0][comment]", type="text", required=false, description="点评说明", sample="")
     * @ApiParams   (name="bed[0][images]", type="text", required=false, description="图片链接 多图以,分割", sample="")
     * @ApiParams   (name="bed[0][behavior_ids]", type="array", required=false, description="点评床位的行为ids", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "成功",
    "time": "1565248642",
    "data": null
    })
     */
    public function addBehaviorRecord()
    {
        // 点评寝室数据
        $dorm_data = $this->request->post('dorm', [], 'strip_tags');
        // 点评床位数据
        $bed_data = $this->request->post('bed', [], 'strip_tags');


       /* \think\Log::info($dorm_data);
        \think\Log::info($bed_data);*/

        //$this->error('', compact('dorm_data', 'bed_data'));

        if ($dorm_data) $dorm_data = json_decode($dorm_data, true);
        if ($bed_data) $bed_data = json_decode($bed_data, true);

        if (!isset($dorm_data['id']))
            $this->error('参数错误, 请先选择要点评的寝室');

        // 获取该寝室
        $dorm = DormitoryDorm::get($dorm_data['id']);

        if (!$dorm)
            $this->error('您要点评的寝室不存在');

        // 新的数组 用于存放所有的行为id
        $behavior_ids = [];

        // 判断是否有寝室点评
        if (isset($dorm_data['behavior_ids']) && $dorm_data['behavior_ids']) {
            // behavior_ids 是否是数组 不是的话转成数组(必须是以,连接)
            if (!is_array($dorm_data['behavior_ids']))
                $dorm_data['behavior_ids'] = explode(',', $dorm_data['behavior_ids']);

            // 存放进behavior_ids
            $behavior_ids = $dorm_data['behavior_ids'];
        } else {
            $dorm_data['behavior_ids'] = [];
        }

        // 新的数组 用于存放床位列表
        $bed_list = [];
        if ($bed_data) {

            foreach ($bed_data as $key => $value) {
                // 判断是否有床位点评
                if (isset($value['behavior_ids']) && $value['behavior_ids']) {
                    // behavior_ids 是否是数组 不是的话转成数组(必须是以,连接)
                    if (!is_array($value['behavior_ids'])) {
                        $bed_data[$key]['behavior_ids'] = explode(',', $value['behavior_ids']);
                    }

                    // 把点评床位的behavior_ids 追加进$behavior_ids
                    $behavior_ids = array_merge($behavior_ids, $bed_data[$key]['behavior_ids']);
                } else {
                    $bed_data[$key]['behavior_ids'] = [];
                }
            }

            // 取出所有的床位信息
            $results = DormitoryDormBed::where('garden_number', $dorm['garden_number'])
                ->where('building_number', $dorm['building_number'])
                ->where('dorm_number', $dorm['number'])
                ->where('status', DormitoryDormBed::ZAIYONG)
                ->where('student_id', '>', 0)
                ->field('id,num,number,student_id')
                ->order('num', 'asc')
                ->select();

            // 重新组合床位信息 便于下面能快速的找到指定的床位
            foreach ($results as $key => $value) {
                $bed_list[$value['id']] = $value;
            }
        }

        // 获取并重新组合行为信息 便于下面能快速的找到指定的行为
        $behavior_list = [];
        if ($behavior_ids) {
            $behavior_ids = array_unique($behavior_ids);
            $results = model\Behavior::whereIn('id', $behavior_ids)->select();
            foreach ($results as $key => $value) {
                $behavior_list[$value['id']] = $value;
            }
        }

        // 要存储的数据
        $insert_detail_data = [];
        // 当前登录用户
        $record_user_id = $this->auth->id;
        $record_user_group = '';
        $group = $this->auth->group;
        if ($group && $group['name']) $record_user_group = $group['name'];

        Db::startTrans();
        try{

            $record = new model\BehaviorRecord;
            $image = new model\BehaviorRecordImage;
            $detail = new model\BehaviorRecordDetail;

            $record->data([
                'record_user_id' => $record_user_id,
                'record_user_group' => $record_user_group,
                'garden_number' => $dorm['garden_number'],
                'building_number' => $dorm['building_number'],
                'dorm_number' => $dorm['number'],
                'comment' => @$dorm_data['comment'],
            ]);
            $record->save();
            $record_id = $record->id;

            if (isset($dorm_data['images']) && $dorm_data['images']) {
                $images = explode(',', $dorm_data['images']);

                $insert_image_data = [];
                foreach ($images as $key => $value) {
                    $insert_image_data[] = [
                        'record_id' => $record_id,
                        'url' => $value,
                    ];
                }

                if ($insert_image_data) {
                    $image->saveAll($insert_image_data);
                }
            }

            // 点评寝室
            $dorm_score = 0;
            $dorm_total_score = 0;
            foreach ($dorm_data['behavior_ids'] as $key => $value) {

                // 查找行为
                if (isset($behavior_list[$value])) {

                    $score = $behavior_list[$value]['type'] == 1 ? $behavior_list[$value]['score'] : $behavior_list[$value]['score'] * (-1);
                    $dorm_total_score = $dorm_score += $score;

                    $insert_detail_data[] = [
                        'record_id' => $record_id,
                        'behavior_id' => $behavior_list[$value]['id'],
                        'behavior_name' => $behavior_list[$value]['name'],
                        'behavior_type' => $behavior_list[$value]['type'],
                        'score' => $score,
                        'behavior_image_id' => $behavior_list[$value]['image_id']
                    ];
                }
            }

            //点评床位(学生)
            $student_score = 0;
            foreach ($bed_data as $k => $v) {
                // 查找床位
                if (isset($bed_list[$v['id']])) {

                    $record->data([
                        'record_user_id' => $record_user_id,
                        'record_user_group' => $record_user_group,
                        'garden_number' => $dorm['garden_number'],
                        'building_number' => $dorm['building_number'],
                        'dorm_number' => $dorm['number'],
                        'bed_number' => $bed_list[$v['id']]['number'],
                        'student_id' => $bed_list[$v['id']]['student_id'],
                        'comment' => @$dorm_data['comment'],
                    ]);
                    $record->isUpdate(false)->save();
                    $record_id = $record->id;

                    if (isset($v['images']) && $v['images']) {
                        $images = explode(',', $v['images']);

                        $insert_image_data = [];
                        foreach ($images as $key => $value) {
                            $insert_image_data[] = [
                                'record_id' => $record_id,
                                'url' => $value,
                            ];
                        }

                        if ($insert_image_data) {
                            $image->isUpdate(false)->saveAll($insert_image_data);
                        }
                    }

                    foreach ($v['behavior_ids'] as $key => $value) {
                        // 查找行为
                        if (isset($behavior_list[$value])) {

                            $score = $behavior_list[$value]['type'] == 1 ? $behavior_list[$value]['score'] : $behavior_list[$value]['score'] * (-1);
                            $student_score += $score;

                            $insert_detail_data[] = [
                                'record_id' => $record_id,
                                'behavior_id' => $behavior_list[$value]['id'],
                                'behavior_name' => $behavior_list[$value]['name'],
                                'behavior_type' => $behavior_list[$value]['type'],
                                'score' => $score,
                                'behavior_image_id' => $behavior_list[$value]['image_id']
                            ];

                            Student::where('id', $bed_list[$v['id']]['student_id'])->setInc('score', $score);
                        }
                    }
                }
            }

            $detail->saveAll($insert_detail_data);

            if (count($bed_list)) $dorm_total_score += (float)number_format($student_score / count($bed_list), 2, '.', '');

            $dorm->setInc('score', $dorm_score);
            $dorm->setInc('total_score', $dorm_total_score);

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            $this->error($e->getMessage() ? $e->getMessage() : '失败');
        }

        $this->success('成功');

    }

    /**
     * @ApiTitle    (点评我的)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/8 16:47)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/recordMe)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="page", type="string", required=false, description="页码", sample="")
     * @ApiParams   (name="filter_time_type", type="int", required=false, description="刷选日期类型 1今天 2昨天 3本周 4上周 5近7天 6本月 7上月 8近30天 9本季度 10上季度 11本年 12上年", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1565767542",
    "data": {
    "summary": {
    "student": {
    "positive": "104",
    "negative": 0
    },
    "dorm": {
    "positive": "96",
    "negative": 0
    }
    },
    "list": {
    "total": 136,
    "per_page": 15,
    "current_page": 1,
    "last_page": 10,
    "data": [
    {
    "id": 134,
    "record_user_id": 22,
    "record_user_group": "学生会",
    "created_at": 1565745296,
    "garden_number": "1",
    "building_number": "9",
    "dorm_number": "9-102",
    "bed_number": "9-10205",
    "student_id": 25,
    "comment": "",
    "record_id": 48,
    "behavior_id": 12,
    "behavior_name": "好人评选",
    "behavior_type": 1,
    "behavior_image_id": 4,
    "score": 5
    }
    ]
    },
    "images": [
    {
    "id": 10,
    "url": "/uploads/20190814/63db68c76ba261e29643fc360021ef5d.png"
    },
    {
    "id": 9,
    "url": "/uploads/20190813/34066da667868a8d83b590408b92ac8a.jpg"
    }
    ]
    }
    })
     */
    public function recordMe()
    {
        // 点评我的
        $user = $this->auth->getUser();

        $student_id = $user['target_id'];

        $data = [];

        $page = $this->request->request('page');
        $filter_time_type = $this->request->request('filter_time_type', 3);
        $date = get_time($filter_time_type, true);

        if ($page < 2) {
            $data['summary']['student'] = model\BehaviorRecord::alias('a')
                ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
                ->where('a.student_id', $student_id)
                ->where('a.created_at', '>=', $date['start_time'])
                ->where('a.created_at', '<=', $date['end_time'])
                ->field('SUM(CASE WHEN b.behavior_type = 1 THEN b.score ELSE 0 END) positive,ABS(SUM(CASE WHEN b.behavior_type = 2 THEN b.score ELSE 0 END)) negative')
                ->find();

            if (!$data['summary']['student']['positive']) $data['summary']['student']['positive'] = 0;
            if (!$data['summary']['student']['negative']) $data['summary']['student']['negative'] = 0;
        }

        // 查找此人现在的床位
        $bed = DormitoryDormBed::where('student_id', $student_id)->where('status', DormitoryDormBed::ZAIYONG)->find();

        if ($bed) {

            if ($page < 2) {
                $data['summary']['dorm'] = model\BehaviorRecord::alias('a')
                    ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
                    ->where('a.garden_number', $bed['garden_number'])
                    ->where('a.building_number', $bed['building_number'])
                    ->where('a.dorm_number', $bed['dorm_number'])
                    ->where('a.student_id', 0)
                    ->where('a.created_at', '>=', $date['start_time'])
                    ->where('a.created_at', '<=', $date['end_time'])
                    ->field('SUM(CASE WHEN b.behavior_type = 1 THEN b.score ELSE 0 END) positive,ABS(SUM(CASE WHEN b.behavior_type = 2 THEN b.score ELSE 0 END)) negative')
                    ->find();

                if (!$data['summary']['dorm']['positive']) $data['summary']['dorm']['positive'] = 0;
                if (!$data['summary']['dorm']['negative']) $data['summary']['dorm']['negative'] = 0;

                $data['images'] = model\BehaviorRecord::alias('a')
                    ->join('__BEHAVIOR_RECORD_IMAGE__ b', 'b.record_id = a.id', 'right')
                    ->where(function ($query) use ($bed) {
                        $query->where([
                            'a.garden_number' => $bed['garden_number'],
                            'a.building_number' => $bed['building_number'],
                            'a.dorm_number' => $bed['dorm_number'],
                        ]);
                    })
                    ->whereOr(function ($query) use ($student_id) {
                        $query->where('a.student_id', $student_id);
                    })
                    ->field('b.id,b.url')
                    ->order('b.id', 'desc')
                    ->limit(5)
                    ->select();

            }

            $data['list'] = model\BehaviorRecord::alias('a')
                ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
                ->join('__DORMITORY_GARDEN__ garden', 'garden.number = a.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ building', 'building.number = a.building_number and building.garden_number = a.garden_number', 'left')
                ->where(function ($query) use ($bed, $date) {
                    $query->where([
                        'a.garden_number'   => $bed['garden_number'],
                        'a.building_number' => $bed['building_number'],
                        'a.dorm_number'     => $bed['dorm_number'],
                    ])->whereBetween('a.created_at', [$date['start_time'], $date['end_time']]);
                })
                ->whereOr(function ($query) use ($student_id, $date) {
                    $query->where([
                        'a.student_id' => $student_id,
                    ])->whereBetween('a.created_at', [$date['start_time'], $date['end_time']]);
                })
                ->field('b.id,a.record_user_id,a.record_user_group,a.created_at,a.student_id,b.behavior_id,b.behavior_name,b.behavior_type,b.score,garden.name garden_name,building.name building_name,a.dorm_number,a.bed_number')
                ->order('a.id', 'desc')
                ->paginate();

            //dd(model\BehaviorRecord::getLastSql());

        } else {

            if ($page < 2) {
                $data['summary']['dorm']['positive'] = 0;
                $data['summary']['dorm']['negative'] = 0;

                $data['images'] = model\BehaviorRecord::alias('a')
                    ->join('__BEHAVIOR_RECORD_IMAGE__ b', 'b.record_id = a.id', 'right')
                    ->where('a.student_id', $student_id)
                    ->field('b.id,b.url')
                    ->order('b.id', 'desc')
                    ->limit(5)
                    ->select();
            }

            $data['list'] = model\BehaviorRecord::alias('a')
                ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
                ->join('__DORMITORY_GARDEN__ garden', 'garden.number = a.garden_number', 'left')
                ->join('__DORMITORY_BUILDING__ building', 'building.number = a.building_number and building.garden_number = a.garden_number', 'left')
                ->where('a.student_id', $student_id)
                ->where('a.created_at', '>=', $date['start_time'])
                ->where('a.created_at', '<=', $date['end_time'])
                ->field('b.id,a.record_user_id,a.record_user_group,a.created_at,a.student_id,b.behavior_id,b.behavior_name,b.behavior_type,b.score,garden.name garden_name,building.name building_name,a.dorm_number,a.bed_number')
                ->order('a.id', 'desc')
                ->paginate();


        }

        $this->success('', $data);

    }

    /**
     * @ApiTitle    (我点评的)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/8 17:08)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/iRecord)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="page", type="string", required=false, description="页码", sample="")
     * @ApiParams   (name="filter_time_type", type="int", required=false, description="刷选日期类型 1今天 2昨天 3本周 4上周 5近7天 6本月 7上月 8近30天 9本季度 10上季度 11本年 12上年", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1565317511",
    "data": {
    "summary": {
    "student": {
    "student_count": 1,
    "positive": "8",
    "negative": "80"
    },
    "dorm": {
    "dorm_count": 2,
    "positive": "8",
    "negative": "80"
    }
    },
    "list": {
    "total": 16,
    "per_page": 15,
    "current_page": 1,
    "last_page": 2,
    "data": [
    {
    "id": 16,
    "behavior_id": 24,
    "behavior_name": "脱贫成果",
    "behavior_type": 2,
    "score": -20,
    "behavior_image_id": 18,
    "record_user_id": 21,
    "record_user_group": "学生会",
    "created_at": 1565317052,
    "garden_number": "1",
    "building_number": "1",
    "dorm_number": "1-101",
    "bed_number": "1-10101",
    "student_id": 2
    }
    ]
    }
    }
    })
     */
    public function iRecord()
    {
        $user_id = $this->auth->id;

        $filter_time_type = $this->request->request('filter_time_type', 3);
        $date = get_time($filter_time_type, true);

        if ($this->request->request('page') < 2) {
            $data['summary']['student'] = model\BehaviorRecord::alias('a')
                ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
                ->where('a.student_id', '>', 0)
                ->where('a.created_at', '>=', $date['start_time'])
                ->where('a.created_at', '<=', $date['end_time'])
                ->field('COUNT(DISTINCT(a.student_id)) student_count,SUM(CASE WHEN b.behavior_type = 1 THEN b.score ELSE 0 END) positive,ABS(SUM(CASE WHEN b.behavior_type = 2 THEN b.score ELSE 0 END)) negative')
                ->find();

            $data['summary']['dorm'] = model\BehaviorRecord::alias('a')
                ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
                ->where('a.student_id', 0)
                ->where('a.created_at', '>=', $date['start_time'])
                ->where('a.created_at', '<=', $date['end_time'])
                ->field('COUNT(DISTINCT(CONCAT(a.garden_number,a.building_number,a.dorm_number))) dorm_count,SUM(CASE WHEN b.behavior_type = 1 THEN b.score ELSE 0 END) positive,ABS(SUM(CASE WHEN b.behavior_type = 2 THEN b.score ELSE 0 END)) negative')
                ->find();

            if (!$data['summary']['student']['positive']) $data['summary']['student']['positive'] = 0;
            if (!$data['summary']['student']['negative']) $data['summary']['student']['negative'] = 0;
            if (!$data['summary']['dorm']['positive']) $data['summary']['dorm']['positive'] = 0;
            if (!$data['summary']['dorm']['negative']) $data['summary']['dorm']['negative'] = 0;
        }

        $data['list'] = model\BehaviorRecord::alias('a')
            ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
            ->join('__DORMITORY_GARDEN__ garden', 'garden.number = a.garden_number', 'left')
            ->join('__DORMITORY_BUILDING__ building', 'building.number = a.building_number and building.garden_number = a.garden_number', 'left')

            ->where('a.record_user_id', $user_id)
            ->where('a.created_at', '>=', $date['start_time'])
            ->where('a.created_at', '<=', $date['end_time'])
            ->field('b.id,a.record_user_id,a.record_user_group,a.created_at,a.student_id,b.behavior_id,b.behavior_name,b.behavior_type,b.score,garden.name garden_name,building.name building_name,a.dorm_number,a.bed_number')
            ->order('b.id', 'desc')
            ->paginate();

        $del_flag = $this->auth->check('behavior/delBehaviorRecord');

        foreach ($data['list'] as $key => $value) {
            if ($value['created_at'] + (7*86400) < time()) {
                $data['list'][$key]['can_del'] = false;
            } else {
                $data['list'][$key]['can_del'] = $del_flag;
            }
        }

        $this->success('', $data);

    }

    /**
     * @ApiTitle    (删除点评记录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/12 11:35)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/behavior/delBehaviorRecord)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="record_id", type="int", required=true, description="记录id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function delBehaviorRecord()
    {
        $record_detail_id = $this->request->post('record_id');

        $record_detail = model\BehaviorRecordDetail::get($record_detail_id);

        if (!$record_detail) if (!$record_detail) $this->error('记录不存在');

        $record = model\BehaviorRecord::where('id', $record_detail['record_id'])->where('record_user_id', $this->auth->id)->find();

        if (!$record) $this->error('记录不存在');

        if ($record['created_at'] + (7*86400) < time()) $this->error('删除失败');

        $dorm = DormitoryDorm::where('garden_number', $record['garden_number'])
            ->where('building_number', $record['building_number'])
            ->where('number', $record['dorm_number'])
            ->find();

        if (!$dorm)
            $this->error('寝室不存在');


        Db::startTrans();
        try{

            // 判断删除的事学生分 还是 寝室分
            if ($record['student_id']) {


                // 需要修改 不能去behavior_record_detail记录表里面取student_count 如果宿舍人数有变动 记录里的人数不准确
                // 更改为根据record的id获取 这一次的点评的记录 根据这个统计出来的人数
                $result = model\BehaviorRecord::alias('a')
                    ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id')
                    ->where('a.garden_number', $record['garden_number'])
                    ->where('a.building_number', $record['building_number'])
                    ->where('a.dorm_number', $record['dorm_number'])
                    ->where('a.student_id', '>', 0)
                    ->where('a.id', $record['id'])
                    ->field('COUNT(DISTINCT(a.student_id)) student_count,SUM(b.score) student_score')
                    ->find();

                $student_count = $result['student_count'] ? $result['student_count'] : 0;
                $student_score = $result['student_score'] ? $result['student_score'] : 0;

                $score = 0;
                if ($student_count)
                    $score = (float)number_format(($student_score - $record_detail['score']) / $student_count, 2, '.', '');

                $dorm->total_score = $dorm['score'] + $score;
                $dorm->save();

                Student::where('id', $record['student_id'])->setDec('score', $record_detail['score']);

            } else {

                $dorm->setDec('score', $record_detail['score']);
                $dorm->setDec('total_score', $record_detail['score']);
            }

            $record_detail->delete();

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            $this->error($e->getMessage() ? $e->getMessage() : '删除失败');
        }

        $this->success('删除成功');
    }




}
